Patchwork is not yet available on CRAN. You’ll need to install it as follows.
library(patchwork)
load('data/starwars_df.RData') # load starwars data frames
bar = people_df %>%
mutate(homeworld = fct_lump(homeworld, n = 4)) %>%
drop_na(homeworld) %>%
ggplot() +
geom_bar(aes(x = homeworld, fill = homeworld), show.legend = F)
smooth = people_df %>%
filter(!is.na(gender) & !grepl(name, pattern = 'Jabba')) %>%
ggplot(aes(x=mass, y=height)) +
geom_point() +
geom_smooth()
scatter = vehicles_df %>%
ggplot(aes(x=length, y=cost_in_credits)) +
geom_point(size = 10, color = '#ff5500') +
geom_text_repel(aes(label = name), size=6, color = 'gray50') # requires ggrepel
box = people_df %>%
mutate(species = fct_lump(species, n = 2)) %>%
drop_na(species) %>%
ggplot(aes(x= species, y = mass)) +
geom_boxplot()Basics. A good way to start is that you create the two separate plots and plotting side by side is the first step. Either of these will work.
If we want the second plot below, you can just use a divisor.
If we have multiple plots, we may want to group them a certain way.
This is what it would look like if we hadn’t nested. Operations take similar mathematical precedence.
We can take this further to use nesting to further enhance the plot.
Layouts provide more customization over the look.
We have additional options.
We can also use it with nesting.
We can alter relative sizes of plots.
box +
smooth +
bar +
scatter +
plot_layout(
ncol = 2, # 2 columns
byrow = T, # enter plots by row
widths = c(1,2), # relative column widths
heights = c(1,1.5) # relative row heights
)You may have some layouts or themes you’d like to apply to each plot. First we’ll start with the usual approach.
We could do the following, but it’s tedious.
Instead, we can just nest/group the plots and use * to apply the theme to all. This is much easier.
Using & will apply through all levels of nesting.
Annotating applies only on the ‘top-level’ plot.
# plot annotation must be applied to the whole set of plots. I nested everything
# so that I could also use the `&` operator for a common theme.
{box / {
smooth +
bar
} &
theme_bw()
} +
plot_annotation(title = 'Star Wars Plots',
subtitle = 'Shenanigans',
theme = theme(title = element_text(size= 24)))